package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApCollectionBehaviorService;
import com.heima.common.constants.article.HotArticleConstants;
import com.heima.common.constants.behavior.BehaviorConstants;
import com.heima.common.constants.mess.app.UpdateArticleMess;
import com.heima.common.exception.CustException;
import com.heima.model.behavior.dtos.CollectionBehaviorDTO;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApCollection;
import com.heima.model.behavior.pojos.ApLikesBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.thread.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Slf4j
@Service
public class ApCollectionBehaviorServiceImpl implements ApCollectionBehaviorService {

    @Autowired
    MongoTemplate mongoTemplate;
    @Resource
    ApBehaviorEntryService behaviorEntryService;
    @Autowired
    RabbitTemplate rabbitTemplate;

    @Override
    public ResponseResult collectBehavior(CollectionBehaviorDTO dto) {
        ApUser user = AppThreadLocalUtils.getUser();
        if (user != null){
//            用户已登录，使用userId
            ApBehaviorEntry behaviorEntry = behaviorEntryService.findByUserIdOrEquipmentId(user.getId(), dto.getEquipmentId());
            if (behaviorEntry == null){
                log.error("collection 1  获取用户行为实体失败,userID为{},equipmentId为{}",user.getId(),dto.getEquipmentId());
                CustException.cust(AppHttpCodeEnum.SERVER_ERROR);
            }
            return operationCollect(behaviorEntry,dto);
        }
//        用户未登录,使用设备ID
        ApBehaviorEntry behaviorEntry = behaviorEntryService.findByUserIdOrEquipmentId(null, dto.getEquipmentId());
        if (behaviorEntry == null){
            log.error("collection 3  获取用户行为实体失败,userID为{},equipmentId为{}",null,dto.getEquipmentId());
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR);
        }
        return  operationCollect(behaviorEntry,dto);
    }

    @Override
    public Boolean check(ApBehaviorEntry behaviorEntry, Long articleId) {

        Query query = Query.query(Criteria.where("entryId").is(behaviorEntry.getId()).and("articleId").is(articleId));
        ApCollection collection = mongoTemplate.findOne(query, ApCollection.class);
        if (collection == null){
            return false;
        }else {
            return true;
        }
    }

    private ResponseResult operationCollect(ApBehaviorEntry behaviorEntry, CollectionBehaviorDTO dto) {
        Short type = dto.getType();
        Short operation = dto.getOperation();
        Long articleId = dto.getArticleId();
        UpdateArticleMess updateArticleMess = new UpdateArticleMess();
//        Query query = Query.query(Criteria.where("entry_id").is(behaviorEntry.getId()).and("type").is(type).and("article_id").is(articleId));
        Query query = Query.query(Criteria.where("entryId").is(behaviorEntry.getId()).and("articleId").is(articleId));
        ApCollection collection = mongoTemplate.findOne(query, ApCollection.class);
        if (collection == null){
//                无记录且行为是0则新增收藏记录
            if (BehaviorConstants.ONE.equals(operation)){
                log.error("collection 重复操作");
                CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
            }
            collection = new ApCollection();
//            collection.setType(type);
            collection.setArticleId(articleId);
            collection.setCollectionTime(new Date());
            collection.setEntryId(behaviorEntry.getId());
            collection = mongoTemplate.save(collection);

//            收藏保存成功，发送MQ消息
            updateArticleMess.setArticleId(collection.getArticleId());
            updateArticleMess.setAdd(1);
            updateArticleMess.setType(UpdateArticleMess.UpdateArticleType.COLLECTION);
            rabbitTemplate.convertAndSend(HotArticleConstants.HOT_ARTICLE_SCORE_BEHAVIOR_QUEUE, JSON.toJSONString(updateArticleMess));
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }else {
//                有记录则检查是否为重复操作
            if (BehaviorConstants.ZERO.equals(operation)){
                log.error("collection 重复操作");
                CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
            }
//                没有重复操作则删除记录
            mongoTemplate.remove(query,ApCollection.class);
            
//            取消收藏保存成功，发送MQ消息
            updateArticleMess.setArticleId(collection.getArticleId());
            updateArticleMess.setAdd(-1);
            updateArticleMess.setType(UpdateArticleMess.UpdateArticleType.COLLECTION);
            rabbitTemplate.convertAndSend(HotArticleConstants.HOT_ARTICLE_SCORE_BEHAVIOR_QUEUE,JSON.toJSONString(updateArticleMess));
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
    }
}
